package com.github.niefy.config;

import com.github.niefy.common.xss.XssFilter;
import com.github.niefy.modules.third.filter.ThirdTokenFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.DispatcherType;
import javax.servlet.http.HttpFilter;

/**
 * Filter配置
 * @author Mark sunlightcs@gmail.com
 */
@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<GenericFilterBean> shiroFilterRegistration() {
        var registration = new FilterRegistrationBean<GenericFilterBean>();
        registration.setFilter(new DelegatingFilterProxy("shiroFilter"));
        //该值缺省为false，表示生命周期由SpringApplicationContext管理，设置为true则表示由ServletContainer管理
        registration.addInitParameter("targetFilterLifecycle", "true");
        registration.setEnabled(true);
        registration.setOrder(Integer.MAX_VALUE - 1);
        registration.addUrlPatterns("/sys/*");
        registration.addUrlPatterns("/manage/*");
        return registration;
    }

    @Bean
    public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
        var registration = new FilterRegistrationBean<XssFilter>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns("/*");
        registration.setName("xssFilter");
        registration.setOrder(Integer.MAX_VALUE);
        return registration;
    }

    @Bean
    public FilterRegistrationBean<HttpFilter> thirdTokenFilterRegistration() {
        var registration = new FilterRegistrationBean<HttpFilter>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new ThirdTokenFilter());
        registration.addUrlPatterns("/third/*");
        registration.addUrlPatterns("/web/*");
        registration.setName("thirdTokenFilter");
        registration.setOrder(Integer.MAX_VALUE - 1);
        return registration;
    }

}
